﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using RabbitMQDemo.Models;
using RabbitMQDemo.Models.demo2;

namespace RabbitMQDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly RabbitMQClient _rabbitMQClient;

        public HomeController(ILogger<HomeController> logger, RabbitMQClient rabbitMQClient)
        {
            _logger = logger;
            _rabbitMQClient = rabbitMQClient;
        }

        public IActionResult Index()
        {

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        /// <summary>
        /// 向队列中发送消息 
        /// </summary>
        /// <param name="msgView"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SendMsg([FromBody]MsgViewModel msgView)
        {
            if (msgView == null || string.IsNullOrWhiteSpace(msgView.content))
            {
                return Json(new { flag = 1, msg = "value is null" });
            }
            //创建连接工厂
            ConnectionFactory factory = new ConnectionFactory
            {
                UserName = "guest",//用户名
                Password = "guest",//密码
                HostName = "127.0.0.1"//rabbitmq ip
            };

            //DirectModel(factory, msgView.content);
          
            _rabbitMQClient.PushMessage("done.tasks", msgView.content);
            

            return Json(new { flag = 0 });
        }

        /// <summary>
        /// 直接模式
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="content"></param>
        static void DirectModel(ConnectionFactory factory, string content)
        {
            //创建连接
            var connection = factory.CreateConnection();
            //创建通道
            var channel = connection.CreateModel();
            //声明一个队列
            channel.QueueDeclare("glzdemo1", false, false, false, null);

            //Console.WriteLine("\nRabbitMQ连接成功，请输入消息，输入exit退出！");

            var sendBytes = Encoding.UTF8.GetBytes(content);
            //发布消息 交換機為null，則是直接模式
            //隊列 glzdemo
            channel.BasicPublish("glzdemo1", "route.key", null, sendBytes);

            channel.Close();
            connection.Close();
        }


        static void Test()
        {
            MQConfig config = new MQConfig()
            {
                HostName = "127.0.0.1",
                Password = "123456",
                Port = 5672,
                UserName = "dotnet"
            };
            MQServcieManager manager = new MQServcieManager();
            manager.AddService(new DemoService(config));
            manager.OnAction = OnActionOutput;
            manager.Start();
            Console.WriteLine("服务已启动");
            Console.ReadKey();
            manager.Stop();
            Console.WriteLine("服务已停止,按任意键退出...");
            Console.ReadKey();
        }
        static void OnActionOutput(MessageLevel level, string message, Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("{0} | {1} | {2}", level, message, ex?.StackTrace);
            Console.ForegroundColor = ConsoleColor.Gray;
        }
    }
}
